﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;

namespace ClassLibrary
{
    public class GoodService
    {
        ItemService itemService = new ItemService();
        OrderService orderService = new OrderService();
        UserService userService = new UserService();
        public GoodService() { }
        public void AddGood(Good good)
        {
            using (var ctx = new SystemContext())
            {
                if (good == null) { return; }
                ctx.Goods.Add(good);
                ctx.SaveChanges();
            }
        }
        public void DeleteGood(Good good)
        {
            using (var ctx = new SystemContext())
            {
                var good1 = ctx.Goods
                    .SingleOrDefault(s => s.GoodID == good.GoodID);

                if (good1 == null) { return; }
                ctx.Goods.Remove(good1);
                ctx.SaveChanges();
            }
        }
        public void ModifyGood(Good newGood)
        {
            DeleteGood(newGood);
            AddGood(newGood);
        }
        public List<Good> GetGoodByOrderID(string orderid)
        {
            using (var ctx = new SystemContext())
            {
                var goods = ctx.Goods.ToList();
                return goods
                    .Where(s => s.OrderID == orderid)
                    .ToList();
            }
        }
        public List<Good> GetGoodByItemID(string itemid)
        {
            using (var ctx = new SystemContext())
            {
                var goods = ctx.Goods.ToList();
                return goods
                    .Where(s => s.ItemID == itemid)
                    .ToList();
            }
        }
        public List<Good> GetGoodsBySellerID(string sellerid)
        {
            using (var ctx = new SystemContext())
            {
                var goods = ctx.Goods.ToList();
                return goods
                    .Where(s => itemService.GetUserByItem(
                        itemService.GetItemByItemID(s.ItemID)[0])[0].UserID == sellerid)
                    .ToList();
            }
        }
        public List<Good> GetGoodsByUserIDandKey(string sellerid, string key)// 根据超市id和关键字搜索
        {
            using (var ctx = new SystemContext())
            {
                return ctx.Goods
                    .Where(s => itemService.GetUserByItem(
                        itemService.GetItemByItemID(s.ItemID)[0])[0].UserID == sellerid
                        && s.GoodName.Contains(key))
                    .ToList();
            }
        }
        public User GetBuyer(Good good)
        {
            return userService.GetUserByID(orderService.GetOrderById(good.OrderID)[0].UserID)[0];
        }
    }
}
